package com.qfedu.fmmall.service.impl.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPay;
import com.qfedu.fmmall.config.MyPayConfig;
import com.qfedu.fmmall.entity.OrderItem;
import com.qfedu.fmmall.entity.Orders;
import com.qfedu.fmmall.entity.ProductSku;
import com.qfedu.fmmall.mapper.OrderItemMapper;
import com.qfedu.fmmall.mapper.OrdersMapper;
import com.qfedu.fmmall.mapper.ProductSkuMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时查询订单状态
 */

@Component
public class OrderTimeCheckJob {
    private  WXPay wxPay=new WXPay(new MyPayConfig());
     @Resource
     private OrdersMapper ordersMapper;
     @Resource
     private OrderItemMapper orderItemMapper;
     @Resource
     private ProductSkuMapper productSkuMapper;
    @Scheduled(cron = "0/60 * * * * ?")
    public void checkAndCloseOderr(){
        LambdaQueryWrapper<Orders> lambda=new LambdaQueryWrapper();
        lambda.eq(Orders::getStatus,"1");
        lambda.lt(Orders::getCreateTime, LocalDateTime.now().minusMinutes(30));
        List<Orders> ordersList = ordersMapper.selectList(lambda);
        for (Orders order:ordersList) {
            //             微信支付请求链接
            try {
            HashMap<String, String> map = new HashMap<>();
            map.put("out_trade_no",order.getOrderId());
            Map<String, String> resp = null;
            resp = wxPay.orderQuery(map);
            if ("SUCCESS".equalsIgnoreCase(resp.get("trade_success"))) {
         //           订单已经支付
               order.setStatus("2");
             ordersMapper.updateById(order);
            } else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_success"))) {
//                关闭订单
                Map<String, String> stringStringMap = wxPay.closeOrder(map);
                if ("SUCCESS".equalsIgnoreCase(stringStringMap.get("success"))) {
                    //                订单没有支付
                    order.setStatus("6");
                    order.setCloseType(1);
                    ordersMapper.updateById(order);
                    List<OrderItem> orderItems = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, order.getOrderId()));
                    for (OrderItem orderItem: orderItems) {
                        ProductSku productSkus = productSkuMapper.selectOne(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getSkuId, orderItem.getSkuId()));
                        productSkus.setStock(productSkus.getStock()+orderItem.getBuyCounts());
                    }
             }
            }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }
    }
}
